package com.example.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.concurrent.ConcurrentLinkedDeque;

public class ConnectionPool {
    private static String driverClassName = "com.mysql.jdbc.Driver";
    private static String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/b_camera?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true&useSSL=false";
    private static String userName = "root";
    private static String password = "123456";

    private static ConcurrentLinkedDeque<Connection> queue;

    public static Connection getConnection(){
        if (queue == null) {
            queue = new ConcurrentLinkedDeque<Connection>();
        }
        if (queue.isEmpty()) {
            for (int i=0;i<10;i++){
                try {
                    Class.forName(driverClassName);
                    Connection connection = DriverManager.getConnection(jdbcUrl, userName, password);
                    connection.setAutoCommit(false);
                    queue.offer(connection);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return queue.poll();
    }

    public static void returnConnection(Connection connection){
        queue.offer(connection);
    }

}
